package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// CheckUserHasActiveBooking 检查用户是否有有效的预订
func CheckUserHasActiveBooking(userID int, storeID int) (bool, error) {
	// 获取当前时间
	now := time.Now()

	// 查询条件：
	// 1. 用户ID匹配
	// 2. 门店ID匹配
	// 3. 订单状态为已确认(1)
	// 4. 当前时间在预订的开始和结束时间之间
	o := orm.NewOrm()
	var count int64

	// 使用原生SQL查询，更灵活地处理时间条件
	sql := `SELECT COUNT(*) FROM ss_order 
		WHERE member_id = ? AND store_id = ? AND status = 2 
		AND ? BETWEEN start_time AND end_time`

	err := o.Raw(sql, userID, storeID, now.Unix()).QueryRow(&count)
	if err != nil {
		return false, err
	}

	return count > 0, nil
}
